/**
 * @description 上传图片加水印
 * @param {File} file 上传的文件对象
 * @param {Object} config 配置项
 * @param {String} config.watermarkText 水印文字
 * @param {Number} config.fillSize 水印文字字号
 * @param {String} config.fillColor 水印文字颜色
 * @param {Number} config.watermarkInterval 水印文字间隔
 * @param {Number} config.watermarkAngle 水印文字旋转角度
 * @param {Number} config.watermarkPadding 水印区域与图片边界间距
 * @param {Number} config.quality 生成图片压缩比 默认 1 不压缩
 * @returns {Promise} Promise file对象
 */
interface WatermarkConfig {
	watermarkText?: string;
	fillSize?: number;
	fillColor?: string;
	watermarkInterval?: number;
	watermarkAngle?: number;
	watermarkPadding?: number;
	quality?: number;
}

const addWaterMarkToFile = async (file: File, config: WatermarkConfig = {}): Promise<File> => {
	if (!file || !file.type.startsWith('image/')) {
		throw new Error('上传的文件不是图片');
	}
	const currentConfig: WatermarkConfig = {
		watermarkText: '水印',
		fillSize: 32,
		fillColor: 'rgba(255,255,255,0.5)',
		watermarkInterval: 150,
		watermarkAngle: 45,
		watermarkPadding: 10,
		quality: 1,
		...config,
	};
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = async () => {
			try {
				const img = new Image();
				img.src = reader.result as string;

				img.onload = async () => {
					const canvas = document.createElement('canvas');
					const ctx = canvas.getContext('2d');

					if (!ctx) {
						reject(new Error('Failed to get canvas context'));
						return;
					}

					// 设置canvas尺寸与图片一致
					canvas.width = img.width;
					canvas.height = img.height;

					// 绘制原始图片
					ctx.drawImage(img, 0, 0, img.width, img.height);

					// 计算水印文本的宽度
					const textWidth = ctx.measureText(currentConfig.watermarkText!).width;

					// 循环在图片上添加水印
					for (
						let x = currentConfig.watermarkPadding!;
						x <= img.width - textWidth - currentConfig.watermarkPadding!;
						x += currentConfig.watermarkInterval!
					) {
						for (
							let y = currentConfig.watermarkPadding!;
							y <= img.height - currentConfig.watermarkPadding!;
							y += currentConfig.watermarkInterval!
						) {
							// 设置水印颜色和透明度
							ctx.fillStyle = currentConfig.fillColor!;
							ctx.font = `${currentConfig.fillSize}px Arial`;

							// 计算水印位置，防止超出边界
							const textX = x;
							const textY = y + currentConfig.fillSize! / 2;
							console.log(`Using font size: ${ctx.font}`, currentConfig.fillSize);
							// 添加水印并倾斜
							ctx.save();
							ctx.translate(textX + textWidth / 2, textY);
							ctx.rotate((currentConfig.watermarkAngle! * Math.PI) / 180);
							ctx.fillText(currentConfig.watermarkText!, 0, 0);
							ctx.restore();
						}
					}

					// 将canvas内容导出为Blob
					canvas.toBlob(
						async newBlob => {
							if (newBlob) {
								// 创建新的File对象
								const watermarkedFile = new File([newBlob], file.name, { type: file.type });
								resolve(watermarkedFile);
							} else {
								reject(new Error('Failed to generate new Blob'));
							}
						},
						file.type,
						currentConfig.quality,
					);
				};

				img.onerror = reject;
			} catch (error) {
				reject(error);
			}
		};

		reader.onerror = reject;
	});
};
export default addWaterMarkToFile;
